import React, { Component } from "react";
import { View, Alert } from "react-native";
import CustomHeader from "../../components/CustomHeader";
import { Input, Button } from "react-native-elements";
import { request } from "../../utils";
import AsyncStorage from "@react-native-community/async-storage";
import DeviceInfo from "react-native-device-info";
import { MyButton } from "../../components/MyButton";

export class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      account: "",
      password: ""
    };
  }
  submit = _ => {
    const { account, password } = this.state;
    const { navigation } = this.props;
    request(
      "user/login",
      { account, password, deviceId: DeviceInfo.getUniqueID() },
      data => {
        global.userInfo = data;
        AsyncStorage.setItem("Token", data.Token);
        navigation.replace("Home");
      },
      data => Alert.alert(data, "")
    );
  };
  tryOut = _ => {
    const { navigation } = this.props;
    request(
      "user/tryOut",
      { deviceId: "tryOut_" + DeviceInfo.getUniqueID() },
      data => {
        global.userInfo = data;
        AsyncStorage.setItem("Token", data.Token);
        navigation.replace("Home");
      },
      data => Alert.alert(data, "")
    );
  };
  render() {
    const { account, password } = this.state;
    const { navigation } = this.props;
    return (
      <View>
        <CustomHeader
          hideBack
          title="登录"
          rightComponent={
            <MyButton
              title="注册"
              type="clear"
              onPress={_ => navigation.navigate("Register")}
            />
          }
        />

        <Input
          placeholder="手机或邮箱"
          containerStyle={{
            marginTop: 100
          }}
          onChangeText={account => this.setState({ account })}
        />
        <Input
          placeholder="密码"
          secureTextEntry={true}
          onChangeText={password => this.setState({ password })}
        />

        <View
          style={{
            display: "flex",
            alignItems: "flex-end"
          }}
        >
          <MyButton
            title="忘记密码?"
            type="clear"
            onPress={_ => navigation.navigate("ForgetPassword")}
          />
        </View>
        <MyButton
          title="登录"
          disabled={!(account && password)}
          onPress={this.submit}
          containerStyle={{
            margin: 36
          }}
        />
        <MyButton
          title="试用"
          onPress={this.tryOut}
          containerStyle={{
            margin: 36
          }}
        />
      </View>
    );
  }
}

export default Login;
